import logging
from docker import APIClient
from systemd.models import registryInfo
from ..models import imageInfo
from ..models import push_log
from ..serializers import ImagePushDataSerializer

CUSTOM_ERROR = logging.getLogger('apps.views')

class Image_Push_opration():
    '''推送镜像'''

    def __init__(self, id_list, remote_env, *args):
        self.id_list = id_list
        self.remote_env = remote_env

    def push_opration(self, user, *args):
        '''推送操作'''

        try:
            registry = registryInfo.objects.filter(env=self.remote_env).values().first()
            # cli = APIClient(base_url='unix:///var/run/docker.sock', timeout=5)
            cli = APIClient(base_url='http://127.0.0.1:2375', timeout=10)
            cli.login(registry=registry.get('registry'),
                      username=registry.get('username'),
                      password=registry.get('password'))
        except Exception as e:
            CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}')
            raise e
        else:
            push_log_data = []
            for image_id in self.id_list:
                # 循环id数据 并通过id获取镜像信息
                image = imageInfo.objects.filter(id=image_id).values().first()
                remote_repo = registryInfo.objects.filter(env=self.remote_env).values().first()
                try:
                    cli.pull(repository=image.get('test'), tag=image.get('tag'))
                    cli.tag(f"{image.get('test')}:{image.get('tag')}", f"{remote_repo.get('registry')}/{remote_repo.get('namespace')}/{image.get('name')}", tag=image.get('tag'))
                    cli.push(f"{remote_repo.get('registry')}/{remote_repo.get('namespace')}/{image.get('name')}", tag=image.get('tag'))
                except Exception as e:
                    # 将推送失败的镜像信息保存至数据库并添加到push_log_data列表，以返回给前端做信息展示。
                    push_log.objects.create(name=image.get('name'),
                                            tag=image.get('tag'),
                                            application_type=image.get('application_type'),
                                            push_env=self.remote_env,
                                            push_user=user,
                                            status=False)
                    queryset = push_log.objects.filter(name=image.get('name')).order_by('-id').values()
                    serializer = ImagePushDataSerializer(queryset, many=True)
                    push_log_data.append(serializer.data[0])
                    logging.error(e)
                    CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}')
                else:
                    # 将推送成功的镜像信息保存至数据库并添加到push_log_data列表，以返回给前端做信息展示。
                    cli.remove_image(f"{image.get('test')}:{image.get('tag')}")
                    cli.remove_image(f"{remote_repo.get('registry')}/{remote_repo.get('namespace')}/{image.get('name')}:{image.get('tag')}")
                    push_log.objects.create(name=image.get('name'),
                                            tag=image.get('tag'),
                                            application_type=image.get('application_type'),
                                            push_env=self.remote_env,
                                            push_user=user,
                                            status=True)
                    queryset = push_log.objects.filter(name=image.get('name')).order_by('-id').values()
                    serializer = ImagePushDataSerializer(queryset, many=True)
                    push_log_data.append(serializer.data[0])

            return push_log_data